package com.jh.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jh.dto.InventoryTransactionSaveDTO;
import com.jh.dto.InventoryTransactionSelectDTO;
import com.jh.dto.OderPageQueryDTO;
import com.jh.dto.ProductPageQueryDTO;
import com.jh.entity.InventoryTransaction;
import com.jh.entity.Product;
import com.jh.entity.ProductDetail;
import com.jh.mapper.ProductMapper;
import com.jh.result.PageResult;
import com.jh.result.Result;
import com.jh.service.InventoryService;
import com.jh.vo.InventoryTransactionDetails;
import com.jh.vo.InventoryTransactionVO;
import com.jh.vo.OrderDetailDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/inventory")
@Slf4j
@Api(tags = "商品库存相关接口")
public class InventoryController {
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private ProductMapper productMapper;

    @GetMapping("/getInventoryData")
    @ApiOperation("商品库存分页查询")
    public Result<PageResult> page(ProductPageQueryDTO productPageQueryDTO){
        log.info("商品库存员工分页查询,employeePageQueryDTO：{}",productPageQueryDTO);
        PageResult pageResult = inventoryService.page(productPageQueryDTO);
        return Result.success(pageResult);
    }

    @DeleteMapping("/deleteBatch")
    @ApiOperation("商品删除")
    public Result delete(@RequestParam List<Long> ids){
        log.info("商品删除，ids:{}",ids);
        inventoryService.deleteBatch(ids);
        return Result.success();
    }

    @PutMapping("/updateInventory")
    @ApiOperation("商品修改")
    public Result updateInventory(@RequestBody Product product){
        log.info("商品修改，product：{}",product);
        inventoryService.update(product);
        return Result.success();
    }

    @PostMapping("/transaction/submit")
    @ApiOperation("库存交易统一接口")
    public Result submitTransaction(
            @RequestHeader("X-Operation-Type") String operationType,
            @RequestBody @Valid InventoryTransactionSaveDTO dto) {
        try {
            log.info("库存交易操作类型: {}, 数据: {}", operationType, dto);

            // 校验操作类型
            if (!"1".equals(operationType) && !"2".equals(operationType)) {
                return Result.error("非法操作类型");
            }

            dto.setType(Integer.parseInt(operationType));

            // 根据类型处理
            if ("1".equals(operationType)) {
                log.info("入库操作，dto:{}", dto);
                inventoryService.processInbound(dto);
            } else {
                log.info("出库操作,dto:{}", dto);
                inventoryService.processOutbound(dto);
            }

            return Result.success();
        } catch (Exception e) {
            log.error("库存交易失败", e);
            return Result.error("1".equals(operationType) ? "入库失败" : "出库失败");
        }
    }

    @GetMapping("/check")
    @ApiOperation("检查库存是否包含该商品")
    public Result check(String skuCode){
        log.info("检查库存是否包含该商品,skuCode：{}",skuCode);
            if(!inventoryService.check(skuCode)){
               return Result.error("不存在该商品");
            }
        return Result.success("存在该商品");
    }

    @GetMapping("/sku/detail")
    @ApiOperation("获取商品详情")
    public Result getSkuDetail(String skuCode) {
        log.info("获取商品详情,skuCode：{}", skuCode);
        try {
            // 调用service获取商品详情
            ProductDetail productDetail = inventoryService.getSkuDetail(skuCode);
            if (productDetail == null) {
                return Result.error("未找到该商品详情");
            }

            // 获取关联的产品信息
            Product product = productMapper.selectById(productDetail.getProductId());
            if (product == null) {
                return Result.error("未找到该商品信息");
            }

            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            data.put("skuCode", productDetail.getSkuCode());
            data.put("brand", product.getBrand());
            data.put("productCode", product.getProductCode());
            data.put("color", product.getColor());
            data.put("sizeType", productDetail.getSizeType());
            data.put("retailPrice", product.getRetailPrice());

            return Result.success(data);
        } catch (Exception e) {
            log.error("获取商品详情失败", e);
            return Result.error("获取商品详情失败");
        }
    }

    @GetMapping("/getInventoryTransaction")
    @ApiOperation("商品出入库单分页查询")
    public Result<PageResult> getInventoryTransaction(InventoryTransactionSelectDTO pageQueryDTO){
        Page<InventoryTransactionVO> pageResult = inventoryService.getInventoryTransaction(pageQueryDTO);
        return Result.success(new PageResult(pageResult.getTotal(), pageResult.getRecords()));
    }

    @GetMapping("/getInventoryTransactionDetails")
    @ApiOperation("商品出入库单分页查询详情")
    public Result getInventoryTransactionDetails(@RequestParam(name = "InventoryTransactionId", required = true) Long InventoryTransactionId){
        List<InventoryTransactionDetails> listResult =inventoryService.getInventoryTransactionDetails(InventoryTransactionId);
        return Result.success(listResult);
    }

    @GetMapping("/checkInventoryTransaction")
    @ApiOperation("商品出入库单确认/删除")
    public Result checkInventoryTransaction(
            @Valid
            @RequestParam(name = "InventoryTransactionId", required = true)
            @NotNull(message = "出入库单号不能为空")
            @ApiParam(name = "InventoryTransactionId", value = "出入库单号", required = true) Long InventoryTransactionId,
            @RequestParam(name = "status", required = true)
            @NotNull(message = "出入库单类型不能为空")
            @ApiParam(name = "status", value = "出入库单类型（2-删除，1-确认）", required = true) Integer status){
        inventoryService.checkInventoryTransaction(InventoryTransactionId, status);
        return Result.success();
    }


}
